const Product = require('../models/Product');
const { successResponse, errorResponse, paginationResponse } = require('../utils/response');
const logger = require('../utils/logger');

// 获取产品列表
exports.getProducts = async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const skip = (page - 1) * limit;
    const sort = req.query.sort || 'createdAt';
    const order = req.query.order === 'asc' ? 1 : -1;
    
    // 查询条件
    const filter = {};
    if (req.query.name) {
      filter.name = { $regex: req.query.name, $options: 'i' };
    }
    if (req.query.category) {
      filter.category = req.query.category;
    }
    if (req.query.status) {
      filter.status = req.query.status;
    }
    if (req.query.minPrice) {
      filter.price = { ...filter.price, $gte: parseInt(req.query.minPrice) };
    }
    if (req.query.maxPrice) {
      filter.price = { ...filter.price, $lte: parseInt(req.query.maxPrice) };
    }

    // 查询产品总数
    const total = await Product.countDocuments(filter);
    
    // 查询产品列表
    const products = await Product.find(filter)
      .populate('createdBy', 'username name')
      .sort({ [sort]: order })
      .skip(skip)
      .limit(limit);

    return paginationResponse(res, products, page, limit, total);
  } catch (error) {
    logger.error(`获取产品列表失败: ${error.message}`);
    return errorResponse(res, '获取产品列表失败', 500);
  }
};

// 获取单个产品
exports.getProduct = async (req, res) => {
  try {
    const product = await Product.findById(req.params.id)
      .populate('createdBy', 'username name');
    
    if (!product) {
      return errorResponse(res, '产品不存在', 404);
    }

    return successResponse(res, product, '获取产品成功');
  } catch (error) {
    logger.error(`获取产品失败: ${error.message}`);
    return errorResponse(res, '获取产品失败', 500);
  }
};

// 创建产品
exports.createProduct = async (req, res) => {
  try {
    const { name, description, price, category, stock, status } = req.body;

    // 创建新产品
    const product = new Product({
      name,
      description,
      price,
      category,
      stock: stock || 0,
      status: status || 'active',
      createdBy: req.user.id
    });

    await product.save();
    return successResponse(res, product, '创建产品成功', 201);
  } catch (error) {
    logger.error(`创建产品失败: ${error.message}`);
    return errorResponse(res, '创建产品失败', 500);
  }
};

// 更新产品
exports.updateProduct = async (req, res) => {
  try {
    const { name, description, price, category, stock, status, images } = req.body;
    
    // 查找产品
    const product = await Product.findById(req.params.id);
    if (!product) {
      return errorResponse(res, '产品不存在', 404);
    }

    // 更新产品信息
    if (name) product.name = name;
    if (description !== undefined) product.description = description;
    if (price) product.price = price;
    if (category) product.category = category;
    if (stock !== undefined) product.stock = stock;
    if (status) product.status = status;
    if (images) product.images = images;

    product.updatedAt = Date.now();
    await product.save();

    return successResponse(res, product, '更新产品成功');
  } catch (error) {
    logger.error(`更新产品失败: ${error.message}`);
    return errorResponse(res, '更新产品失败', 500);
  }
};

// 删除产品
exports.deleteProduct = async (req, res) => {
  try {
    const product = await Product.findById(req.params.id);
    if (!product) {
      return errorResponse(res, '产品不存在', 404);
    }

    await product.remove();
    return successResponse(res, null, '删除产品成功');
  } catch (error) {
    logger.error(`删除产品失败: ${error.message}`);
    return errorResponse(res, '删除产品失败', 500);
  }
}; 